package com.opencee.cloud.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.opencee.cloud.base.api.IBaseUserApi;
import com.opencee.cloud.base.entity.BaseUserEntity;
import com.opencee.cloud.base.service.IBaseAccountCredentialService;
import com.opencee.cloud.base.service.IBaseOrganizationService;
import com.opencee.cloud.base.service.IBasePrivilegesService;
import com.opencee.cloud.base.service.IBaseUserService;
import com.opencee.cloud.base.vo.*;
import com.opencee.common.exception.BaseFailException;
import com.opencee.common.model.ApiResult;
import com.opencee.common.model.PageQuery;
import com.opencee.common.model.PageResult;
import com.opencee.common.security.SecurityHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统用户信息
 *
 * @author liuyadu
 */
@Api(tags = "人员")
@RestController
@RequestMapping("/user")
public class BaseUserController implements IBaseUserApi {
    @Autowired
    private IBaseUserService userService;
    @Autowired
    private IBaseAccountCredentialService baseAccountCredentialService;
    @Autowired
    private IBasePrivilegesService privilegesService;
    @Autowired
    private IBaseOrganizationService organizationService;

    /**
     * 查询当前用户信息
     *
     * @return
     */
    @ApiOperation(value = "查询当前用户信息", notes = "查询当前用户信息")
    @GetMapping("/my")
    public ApiResult<BaseMenuVO> my(@RequestParam("sid") String sid) {
        BaseUserInfoVO userInfoVo = userService.getUserInfo(SecurityHelper.getUserId());
        if (userInfoVo == null) {
            throw new BaseFailException("用户信息不存在");
        }
        BaseUserPrivilegesVO current = new BaseUserPrivilegesVO();
        BeanUtils.copyProperties(userInfoVo, current);
        Set<Long> roleSet = current.getRoles().stream().map(t -> t.getId()).collect(Collectors.toSet());
        if (!roleSet.isEmpty()) {
            current.setSid(sid);
            // 查询角色相关权限
            List<BaseMenuVO> menus = privilegesService.listRoleGrantedMenu(sid, roleSet, true);
            current.setMenus(menus);
        }
        return ApiResult.ok().data(current);
    }

    @ApiOperation(value = "查询当前用户账号状态", notes = "查询当前用户账号状态")
    @GetMapping("/my/account-status")
    public ApiResult<BaseAccountStatusVO> myAccountStatus() {
        return ApiResult.ok().data(baseAccountCredentialService.listAccountStatus(SecurityHelper.getUserId()));
    }

    /**
     * 查询用户分页列表
     *
     * @return
     */
    @ApiOperation(value = "查询用户分页列表", notes = "查询用户分页列表")
    @GetMapping("/page")
    public ApiResult<PageResult<BaseUserInfoVO>> listPage(PageQuery pageQuery, BaseUserEntity entity, @RequestParam(value = "userIds", required = false) Set<Long> userIds) {
        IPage<BaseUserEntity> page = pageQuery.buildIPage();
        QueryWrapper<BaseUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(ObjectUtils.isNotEmpty(userIds), BaseUserEntity::getUserId, userIds)
                .and(ObjectUtils.isNotEmpty(entity.getUserNo()), w -> w.like(BaseUserEntity::getUserNo, entity.getUserNo())
                        .or()
                        .like(BaseUserEntity::getFullName, entity.getUserNo())
                        .or()
                        .like(BaseUserEntity::getUserName, entity.getUserName()));
        page = userService.page(page, wrapper);
        List<BaseUserInfoVO> list = this.convertList(page.getRecords());
        PageResult result = new PageResult();
        result.setRecords(list);
        result.setTotal((int) page.getTotal());
        return ApiResult.ok().data(result);
    }

    private List<BaseUserInfoVO> convertList(List<BaseUserEntity> entityList) {
        Set<Long> orgIds = entityList.stream().filter(t -> t.getOrgId() != null).map(t -> t.getOrgId()).collect(Collectors.toSet());
        Set<Long> leaderUserIds = entityList.stream().filter(t -> t.getLeaderUserId() != null).map(t -> t.getLeaderUserId()).collect(Collectors.toSet());
        Map<Long, BaseOrganizationVO> orgMap = organizationService.mapByIds(orgIds);
        Map<Long, BaseUserEntity> leaderMap = userService.mapByIds(leaderUserIds);
        return entityList.stream().map(t -> {
            BaseUserInfoVO vo = new BaseUserInfoVO();
            BeanUtils.copyProperties(t, vo);
            BaseOrganizationVO org = orgMap.get(t.getOrgId());
            if (org != null) {
                vo.setOrgName(org.getName());
            }
            BaseUserEntity leader = leaderMap.get(t.getLeaderUserId());
            if (leader != null) {
                vo.setLeaderUserName(leader.getFullName());
                vo.setLeaderUserNo(leader.getUserNo());
            }
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 查询详情
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "查询详情", notes = "基本信息")
    @GetMapping("/getById")
    @Override
    public ApiResult<BaseUserEntity> getById(@RequestParam(value = "userId") Long userId) {
        return ApiResult.ok().data(userService.getById(userId));
    }

    /**
     * 查询详情(角色、组织机构)
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "查询详情", notes = "基本信息、角色、组织机构")
    @GetMapping("/getInfoById")
    @Override
    public ApiResult<BaseUserInfoVO> getInfoById(@RequestParam(value = "userId") Long userId) {
        return ApiResult.ok().data(userService.getUserInfo(userId));
    }

    /**
     * 查询列表
     *
     * @param entity
     * @param userIds
     * @return
     */
    @ApiOperation(value = "查询列表", notes = "支持条件查询和批量查询")
    @GetMapping("/getList")
    @Override
    public ApiResult<List<BaseUserInfoVO>> getList(BaseUserEntity entity, @RequestParam(value = "userIds", required = false) Set<Long> userIds) {
        QueryWrapper<BaseUserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(ObjectUtils.isNotEmpty(userIds), BaseUserEntity::getUserId, userIds)
                .like(ObjectUtils.isNotEmpty(entity.getMobile()), BaseUserEntity::getMobile, entity.getMobile())
                .like(ObjectUtils.isNotEmpty(entity.getUserName()), BaseUserEntity::getUserName, entity.getUserName())
                .like(ObjectUtils.isNotEmpty(entity.getFullName()), BaseUserEntity::getFullName, entity.getFullName())
                .and(ObjectUtils.isNotEmpty(entity.getUserNo()), w -> w.like(BaseUserEntity::getUserNo, entity.getUserNo())
                        .or()
                        .like(BaseUserEntity::getFullName, entity.getUserNo()));
        List<BaseUserEntity> entityList = userService.list(wrapper);
        List<BaseUserInfoVO> list = this.convertList(entityList);
        return ApiResult.ok().data(list);
    }

    /**
     * 批量查询返回Map
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量查询返回Map", notes = "批量查询返回Map")
    @GetMapping("/getMapByIds")
    @Override
    public ApiResult<Map<Long, BaseUserEntity>> getMapByIds(@RequestParam(value = "ids") Set<Long> ids) {
        return ApiResult.ok().data(userService.mapByIds(ids));
    }

    /**
     * 批量查询返回List
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量查询返回List", notes = "批量查询返回List")
    @GetMapping("/getListByIds")
    @Override
    public ApiResult<List<BaseUserEntity>> getListByIds(@RequestParam(value = "ids") Set<Long> ids) {
        return ApiResult.ok().data(userService.listByIds(ids));
    }

    /**
     * 新增/修改用户
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "新增/修改用户", notes = "新增/修改用户")
    @PostMapping("/save")
    @Override
    public ApiResult<Long> save(@RequestBody BaseUserInfoVO user) {
        userService.saveUserInfo(user);
        return ApiResult.ok().data(user.getUserId());
    }


}
